import orderCard from "./component/orderCard";
import memberCard from "./component/memberCard";
import areaCard from "./component/areaCard";
import mapCard from "./component/mapCard";
import leftQuarterCard from "./component/bottom/leftQuarterCard";
import middleQuarterCard from "./component/bottom/middleQuarterCard";
import rightQuarterCard from "./component/bottom/rightQuarterCard";
import countTo from "vue-count-to";
export default {
  data() {
    return {
      isShow: false,
      province: [],
      screen_name:"",
      total_member: "",
      total_sales:"",
      ockReconnect: false, //是否真正建立连接
      timeout: 3 * 1000, //todo 30秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      isClosed: false, //是否关闭ws
      lockReconnect: false, //锁定重连状态
      maxReconnectNum: 11, //最大重连次数
      currentReconnectNum: 0, //当前重连次数
      quarter:[],
      kickback:[], //佣金
      order:[], //实时订单
      nowTime:"", //当前时间
      ininValue: "",//初始化值
    };
  },
  mounted() {
    this.initWebSocket();
    this.timer = setInterval(() => {
      this.nowTime = this.getTime(); // 修改数据date
    }, 1000);
  },
  methods: {
    getTime() {
      let date1 = new Date();
      let year = date1.getFullYear();
      let month =
        date1.getMonth() + 1 < 10
          ? '0' + (date1.getMonth() + 1)
          : date1.getMonth() + 1;
      let day = date1.getDate() < 10 ? '0' + date1.getDate() : date1.getDate();
      let hours =
        date1.getHours() < 10 ? '0' + date1.getHours() : date1.getHours();
      let minutes =
        date1.getMinutes() < 10 ? '0' + date1.getMinutes() : date1.getMinutes();
      let seconds =
        date1.getSeconds() < 10 ? '0' + date1.getSeconds() : date1.getSeconds();
      return (
        year +
        '年' +
        month +
        '月' +
        day +
        '日' +
        hours +
        ' : ' +
        minutes +
        ' : ' +
        seconds
      );
    },
    initWebSocket() {
      //初始化weosocket
      $http
        .get("plugin.large-screen.frontend.controllers.page.index")
        .then(response => {
          console.log(response, "获取数据",document.location.hostname);
          if (response.result === 1) {
            this.province = response.data.province;
            this.total_member =  response.data.total_member;
            this.total_sales = response.data.total_sales;
            this.kickback = response.data.kickback;
            this.order = response.data.order;
            this.member = response.data.member;
            this.quarter = response.data.quarter;
            this.screen_name = response.data.screen_name;
            this.ininValue = true;

            this.websock = new WebSocket(`wss://${document.location.hostname}//ws`);
            // this.websock = new WebSocket("wss://dev15.yunzmall.com//ws");
            this.websock.onmessage = this.websocketonmessage;
            this.websock.onopen = this.websocketonopen;
            this.websock.onerror = this.websocketonerror;
            this.websock.onclose = this.websocketclose;

            console.log("连接建立");
            this.isShow = true;
          } else {
            this.$message.error(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
      console.log("连接建立");
    },
    //连接建立之后执行send方法发送数据
    websocketonopen() {
      // console.log('连接建立之后执行send方法发送数据')
      this.heartBeatStart();
    },
    //连接建立失败重连
    websocketonerror(e) {
      // console.log("连接建立失败重连", e);
    },
    //关闭
    websocketclose(e) {
      // console.log("断开连接", this.isClosed);
      // this.clearHeartBeat();
      if (!this.isClosed) {
        this.reconnect();
      }
    },
    clearHeartBeat() {
      clearInterval(this.heartBeatInterval);
      this.heartBeatInterval = null;
    },
    // 数据接收
    websocketonmessage(e) {
      console.log("后端接收过来的信息",e);
      if (e.data != "pong") {
        console.log("JSON: 后端接收过来的信息",JSON.parse(e.data));
        if(JSON.parse(e.data).result) { return }
        this.isShow = false;
        let data = JSON.parse(e.data);
        this.province = data.province;
        this.total_member =  data.total_member;
        this.total_sales = data.total_sales;
        this.kickback = data.kickback;
        this.order = data.order;
        this.member = data.member;
        this.quarter = data.quarter;
        this.screen_name = data.screen_name;
        this.ininValue = false;
        this.isShow = true;
      }
    },
    readcookie(name) {
      var cookievalue = "";
      var search = name + "=";
      if (document.cookie.length > 0) {
        let offset = document.cookie.indexOf(search);
        if (offset != -1) {
          offset += search.length;
          let end = document.cookie.indexOf(";", offset);
          if (end == -1) end = document.cookie.length;
          cookievalue = unescape(document.cookie.substring(offset, end));
        }
      }
      return cookievalue;
    },
    heartBeatStart() {
      let session_id = this.readcookie("PHPSESSID");
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      this.timeoutObj = setTimeout(() => {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (this.websock.readyState == 1) {
          //如果连接正常
          // this.websock.send(
          //   JSON.stringify({
          //     type: "login",
          //     data: { session_id: session_id },
          //   })
          // );

          this.websock.send(
            JSON.stringify({
              type: "register",
              data: { group: 'large-screen-update'},
            })
          );

          this.keepHeartBeat();
          this.currentReconnectNum = 0; //连接成功归零
        } else {
          //否则重连
          this.reconnect();
        }
      }, this.timeout);
    },
    keepHeartBeat() {
      this.heartBeatInterval = setInterval(() => {
        // 每隔5秒发送一个心跳包消息
        this.websock.send(JSON.stringify({ type: "`ping`" }));
      }, 5000);
    },
    reconnect() {
      //重新连接
      if (this.lockReconnect || this.isClosed || this.currentReconnectNum >= this.maxReconnectNum) {
        if (this.websock) {
          this.websock.close();
        }
        return;
      }
      this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum);
      this.timeoutnum = setTimeout(() => {
        //新连接
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000);
    }
  },
  components: { orderCard, memberCard, areaCard, mapCard, leftQuarterCard, middleQuarterCard, rightQuarterCard, countTo }
};
